Ext.define('appfe.stockor.exec.ExecHoldController', {
	extend: 'Ext.app.ViewController',
	alias: 'controller.stockor.exec.ExecHold',
	/**
	 * 点击查询按钮的查询方法
	 */
	search: function (button, clickEnven) {
		var myview = this.getView();
		myview.getSelectionModel().clearSelections();
		var params = this.assembleSearchParams();
		if (params) {
			//myview.store.removeAll();
			myview.store.getProxy().extraParams = params;
			myview.store.load({
				params: params,
				callback: function (records, operation, success) {
					// console.debug(records);
				}
			});
		}
	},
	/**
	 * 拼接查询参数
	 */
	assembleSearchParams: function () {
		var params = {};
		var queryKey = this.lookup('queryKey').getValue();
		var queryValue = this.lookup('queryValue').getValue();
		if (queryKey && queryValue) {
			params[queryKey] = queryValue;
		}
		var status = this.lookup('status').getValue();
		if (status) {
			params['status'] = status;
		}
		//console.debug('params', params);
		return params;
	},
	onRefreshIntervalChange: function (thisEmt, newValue, oldValue, eOpts) {
		//console.debug('newValue', newValue);
		var me = this;
		var myview = this.getView();
		var myviewmodel = myview.getViewModel();
		this.refreshTaskRunner = Ext.destroy(this.refreshTaskRunner);

		if (newValue != 0) {
			myview.getSelectionModel().clearSelections();
			myview.getSelectionModel().setLocked(true);
			myviewmodel.set('refreshing', true);
			var runner = this.refreshTaskRunner;
			if (!runner) {
				this.refreshTaskRunner = runner = new Ext.util.TaskRunner();
			}
			runner.start({
				run: function () {
					//console.debug(Ext.Date.format(new Date(), 'Y-m-d H:i:s'));
					me.search();
				},
				interval: newValue
			});
		} else {
			myviewmodel.set('refreshing', false);
			myview.getSelectionModel().setLocked(false);
		}
	},
	viewCellIdRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var stkname = record.get('name');
		var slimsymbol = record.get('slimsymbol');
		var grade = record.get('grade');
		var changeTypeFmtStr = "<a href=\"javascript:void(0)\"; onclick=\"javascript:"
			+ "Ext.getCmp('main-tab-panel').getActiveTab().fireEvent('popupLogWin','{0}','{1}','{2}','{3}')\">{0}</a>";
		//+ "console.debug(Ext.getCmp('main-tab-panel'));console.debug(Ext.getCmp('main-tab-panel').getActiveTab());\">{0}</a>";
		return Ext.String.format(changeTypeFmtStr, value, stkname, slimsymbol, grade);
	},
	viewCellSymbolRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var stkname = record.get('name');
		return Ext.String.format("<a href=\"https://xueqiu.com/S/{0}\" target=\"_blank\">{0}</a><br/>{1}", value, stkname);
	},
	viewCellCostRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var unitCost = record.get('unitCost');
		var totalCost = record.get('totalCost');
		return Ext.util.Format.number(unitCost, '￥0.00') + '<br/>' + Ext.util.Format.number(totalCost, '￥0.00');
	},
	viewCellProfitAmountRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		//console.group('viewCellProfitAmountRender');
		var unitCost = record.get('unitCost');
		var current = record.get('current');
		var holdVolume = record.get('holdVolume');
		var unitProfit, totalProfit;
		if (current && holdVolume != 0) {
			unitProfit = current - unitCost;
			totalProfit = unitProfit * holdVolume;
		}

		//record.set('unitProfit', unitProfit);
		//record.set('totalProfit', totalProfit);
		if (unitProfit > 0) {
			metaData.tdStyle = 'color:#dd2200';
		} else if (unitProfit < 0) {
			metaData.tdStyle = 'background-color:#73b51e; color:white';
		}
		return (unitProfit > 0 ? '+' : '') + Ext.util.Format.number(unitProfit, '0.00') + '<br/>' + (totalProfit > 0 ? '+' : '') + Ext.util.Format.number(totalProfit, '0.00');
	},
	viewCellProfitRatioRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var unitCost = record.get('unitCost');
		var current = record.get('current');
		var profitRatio;
		if (current) {
			profitRatio = (current - unitCost) / unitCost;
		}
		if (profitRatio > 0 && profitRatio <= 0.1) {
			metaData.tdStyle = 'background-color:red; font-size: 26px;font-weight: bold;vertical-align: bottom;color: white';
		} else if (profitRatio > 0.1) {
			metaData.tdStyle = 'background-color:DarKRed; font-size: 26px;font-weight: bold;vertical-align: bottom;color: white';
		} else if (profitRatio < 0) {
			metaData.tdStyle = 'background-color:green; font-size: 26px;font-weight: bold;vertical-align: bottom;color: white';
		}
		return (profitRatio > 0 ? '+' : '') + Ext.util.Format.number(profitRatio * 100, '0.00%'); /*利润率*/
	},
	viewCellCurrentRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var percent = record.get('percent');
		if (percent > 0) {
			metaData.tdStyle = 'font-size:26px;font-weight:bold;vertical-align:bottom;color: #dd2200';
		} else if (percent < 0) {
			metaData.tdStyle = 'font-size: 26px;font-weight: bold;vertical-align: bottom;color: #009933';
		} else {
			metaData.tdStyle = 'font-size: 26px;font-weight: bold;vertical-align: bottom;';
		}
		return '<span style="font-size: 16px;font-weight: bold;">￥</span>' + Ext.util.Format.number(value, '0.00');
	},
	viewCellChgPercentRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var chg = record.get('chg');
		var percent = record.get('percent');
		if (value > 0) {
			metaData.tdStyle = 'color:#dd2200';
		} else if (value < 0) {
			metaData.tdStyle = 'color:#009933';
		}
		return (value > 0 ? '+' : '') + Ext.util.Format.number(chg, '0.00') + '<br/>' + (value > 0 ? '+' : '') + Ext.util.Format.number(percent, '0.00%'); /*利润率*/
	},
	viewCellOpenLastcloseRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var open = record.get('open');
		var lastClose = record.get('lastClose');
		var openColor;
		if (open > lastClose) {
			openColor = 'color: #dd2200';
		} else if (open < lastClose) {
			openColor = 'color: #009933';
		}
		var closeColor;
		return '<span style="' + openColor + '">' + Ext.util.Format.number(open, '￥0.00') + '</span><br/><span style="' + closeColor + '">' + Ext.util.Format.number(lastClose, '￥0.00') + '</span>';

	},
	viewCellHighLowRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var lastClose = record.get('lastClose');
		var high = record.get('high');
		var low = record.get('low');
		var highColor;
		if (high > lastClose) {
			highColor = 'color: #dd2200';
		} else if (high < lastClose) {
			highColor = 'color: #009933';
		}
		var lowColor;
		if (low > lastClose) {
			lowColor = 'color: #dd2200';
		} else if (low < lastClose) {
			lowColor = 'color: #009933';
		}
		return '<span style="' + highColor + '">' + Ext.util.Format.number(high, '￥0.00') + '</span><br/><span style="' + lowColor + '">' + Ext.util.Format.number(low, '￥0.00') + '</span>';
	},
	viewCellVolumeAmountRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var volume = record.get('volume');
		var amount = record.get('amount');
		return Ext.util.Format.number(volume / 10000, '0.00') + '<br/>' + Ext.util.Format.number(amount / 100000000, '￥0.00');
	},
	viewCellStatusRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		if (value == 'SOLD') {
			metaData.tdAttr = 'bgcolor="#696969"';
			metaData.tdStyle = 'color:white';
			//metaData.tdStyle = 'color:#dd2200';
		} else if (value == 'WACH') {
			metaData.tdAttr = 'bgcolor="#c9c9c9"';
		}
		return value;
	},
	viewCellPlainTextRender: function (value) {/** grid cell 将html特殊字符替换 */
		//Ext.util.Format.ellipsis(string value, Number length);//截取指定length字符，将自动在尾处添加省略号'...'
		return Ext.util.Format.htmlEncode(value);
	},

	viewCellBooleanRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		if (value == true) {
			metaData.tdAttr = 'bgcolor="#00A800"';
			metaData.tdStyle = 'color:white';
			return '是';
		} else {
			metaData.tdAttr = 'bgcolor="LightGrey"';
			return '否';
		}
	},

	monitorSelloutPriceCellRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		if (Ext.typeOf(value) != 'number' && Ext.Object.isEmpty(value)) {
			return value;
		}
		var unitCost = record.get('unitCost');
		if (value - unitCost > 0) {
			metaData.tdAttr = 'bgcolor="red"';
			metaData.tdStyle = 'color:white';
		} else if (value - unitCost < 0) {
			metaData.tdAttr = 'bgcolor="green"';
			metaData.tdStyle = 'color:white';
		}
		return Ext.util.Format.number(value, '￥0.00');
	},

	monitorSelloutExecProfitCellRender: function (value, metaData, record, rowIndex, colIndex, store, view) {
		var monitorSelloutExecPrice = record.get('monitorSelloutExecPrice');
		if (Ext.typeOf(monitorSelloutExecPrice) != 'number' && Ext.Object.isEmpty(monitorSelloutExecPrice)) {
			return value;
		}
		var monitorSelloutExecVolume = record.get('monitorSelloutExecVolume');
		if (Ext.typeOf(monitorSelloutExecVolume) != 'number' && Ext.Object.isEmpty(monitorSelloutExecVolume)) {
			return value;
		}

		var unitCost = record.get('unitCost');
		var monitorSelloutExecPrice = record.get('monitorSelloutExecPrice');
		var monitorSelloutExecVolume = record.get('monitorSelloutExecVolume');

		var monitorSelloutExecProfit = (monitorSelloutExecPrice - unitCost) * monitorSelloutExecVolume;
		if (monitorSelloutExecProfit > 0) {
			metaData.tdAttr = 'bgcolor="red"';
			metaData.tdStyle = 'color:white';
		} else if (monitorSelloutExecProfit < 0) {
			metaData.tdAttr = 'bgcolor="green"';
			metaData.tdStyle = 'color:white';
		}


		return Ext.util.Format.number(monitorSelloutExecProfit, '￥0.00');
	},
	onBoxReady: function () {

	},
	onRender: function () {
		var mainapp = appfe.getApplication();
		mainapp.addToolTip(this.lookup('queryValue').id, '多个值由逗号分隔');
	},
	/**
	 * 
	 */
	popupFormWin: function (btn) {
		var myview = this.getView();
		var slimsymbol, stkName, holdVolume, unitCost, status, comments;

		if (btn.actionType === 'insert') {
			console.debug('新建');
		} else if (btn.actionType === 'update') {
			console.debug('修改');
			var selRec = this._getSingleSelRec(this.getView().getSelectionModel().getSelection());
			if (!selRec) {
				return;
			}
			slimsymbol = selRec.get('slimsymbol');
			stkName = selRec.get('name');
			holdVolume = selRec.get('holdVolume');
			unitCost = selRec.get('unitCost');
			status = selRec.get('status');
			comments = selRec.get('comments');
		} else {
			Ext.MessageBox.alert('提示', '不能识别的动作类型:' + btn.actionType);
			return;
		}
		var popWin = Ext.widget("window", {
			//title: '持仓编辑',
			layout: 'fit',
			width: 600,
			height: 500,
			minWidth: 600,
			minHeight: 500,
			border: false,
			plain: true,
			modal: true,
			items: [{ xtype: "stockor.exec.form.ExecHoldEditForm" }]
		});
		var popWinPanel = popWin.getComponent(0); //获取form view
		var popWinViewModel = popWinPanel.getViewModel(); //获取view的viewmodel
		popWinViewModel.set('parentItemId', myview.id); //本组建view的itemid, 方便弹窗调用方法
		popWinViewModel.set('actionType', btn.actionType);
		popWinViewModel.set('isValidSlimsymbol', true);
		popWinViewModel.set('holdStock.slimsymbol', slimsymbol);
		popWinViewModel.set('holdStock.stkName', stkName);
		popWinViewModel.set('holdStock.holdVolume', holdVolume);
		popWinViewModel.set('holdStock.unitCost', unitCost);
		popWinViewModel.set('holdStock.status', status);
		popWinViewModel.set('holdStock.comments', comments);

		this.getView().add(popWin);
		popWin.show();

		var winheight = popWin.getHeight(); //获取初始化后窗口的宽度
		var winwidth = popWin.getWidth(); //获取初始化后窗口的高度
		if (winheight - 10 > screenY) { //判断窗口高度是否小于浏览器的窗口高度(留有10px的余量)
			popWin.setHeight(screenY - 30); //设置高度适应浏览器高度(底部留有30px余量，顶部还有10px)
			popWin.setWidth(winwidth + 30); //因为出现了滚动条，增加显示滚动条的宽度
		}
	},
	onBtnDelClick: function () {
		console.debug('底部工具条删除按钮事件');
		var myview = this.getView();
		var myviewmodel = myview.getViewModel();
		var selRec = this._getSingleSelRec(myview.getSelectionModel().getSelection());
		if (!selRec) {
			return;
		}
		var slimsymbol = selRec.get('slimsymbol');
		var stkName = selRec.get('name');
		Ext.MessageBox.confirm('信息提示', '确认要删除[<b>' + slimsymbol + '&nbsp;&nbsp;' + stkName + '</b>]？', function (_btn) {
			if (_btn == 'yes') {
				Ext.Ajax.request({
					url: BizHttpAction.deleteExecStockHold.url,
					method: BizHttpAction.deleteExecStockHold.method,
					params: { slimsymbol: selRec.get('slimsymbol') },
					disableCaching: false,
					success: function (response, opts) {
						var respObj = Ext.JSON.decode(response.responseText);
						if (respObj.success == true) {
							//Ext.MessageBox.alert('提示', '删除成功');
							myviewmodel.getStore('execHoldStore').remove(selRec);
						} else {
							Ext.MessageBox.alert('提示', respObj.message);
						}
					},
					failure: function (response, opts) {
						var respObj = Ext.JSON.decode(response.responseText);
						Ext.MessageBox.alert('提示', respObj.message);
					}
				});
			}
		});
	},
	/**
	 * 
	 */
	popupMonitorWin: function (btn) {
		var myview = this.getView();
		var selRec = this._getSingleSelRec(this.getView().getSelectionModel().getSelection());
		if (!selRec) {
			return;
		}
		var slimsymbol = selRec.get('slimsymbol');
		var stkName = selRec.get('name');
		var holdVolume = selRec.get('holdVolume');
		var unitCost = selRec.get('unitCost');
		var monitorSelloutBarriePrice = selRec.get('monitorSelloutBarriePrice');
		var monitorSelloutExecPrice = selRec.get('monitorSelloutExecPrice');
		var monitorSelloutExecVolume = selRec.get('monitorSelloutExecVolume');

		var popWin = Ext.widget("window", {
			//title: '持仓编辑',
			layout: 'fit',
			width: 600,
			height: 600,
			minWidth: 600,
			minHeight: 500,
			border: false,
			plain: true,
			modal: true,
			items: [{ xtype: "stockor.exec.form.ExecHoldMonitorEditForm" }]
		});
		var popWinPanel = popWin.getComponent(0); //获取form view
		var popWinViewModel = popWinPanel.getViewModel(); //获取view的viewmodel
		popWinViewModel.set('parentItemId', myview.id); //本组建view的itemid, 方便弹窗调用方法
		popWinViewModel.set('isValidSlimsymbol', true);
		popWinViewModel.set('holdStock.slimsymbol', slimsymbol);
		popWinViewModel.set('holdStock.stkName', stkName);
		popWinViewModel.set('holdStock.holdVolume', holdVolume);
		popWinViewModel.set('holdStock.unitCost', unitCost);
		popWinViewModel.set('holdStock.monitorSelloutBarriePrice', monitorSelloutBarriePrice);
		popWinViewModel.set('holdStock.monitorSelloutExecPrice', monitorSelloutExecPrice);
		popWinViewModel.set('holdStock.monitorSelloutExecVolume', monitorSelloutExecVolume);

		this.getView().add(popWin);
		popWin.show();

		var winheight = popWin.getHeight(); //获取初始化后窗口的宽度
		var winwidth = popWin.getWidth(); //获取初始化后窗口的高度
		if (winheight - 10 > screenY) { //判断窗口高度是否小于浏览器的窗口高度(留有10px的余量)
			popWin.setHeight(screenY - 30); //设置高度适应浏览器高度(底部留有30px余量，顶部还有10px)
			popWin.setWidth(winwidth + 30); //因为出现了滚动条，增加显示滚动条的宽度
		}
	},
	fetchCurrentPrice2SelloutAnalyze: function () {
		Ext.Ajax.request({
			url: BizHttpAction.fetchCurrentPrice2SelloutAnalyze.url,
			method: BizHttpAction.fetchCurrentPrice2SelloutAnalyze.method,
			disableCaching: false,
			success: function (response, opts) {
				var respObj = Ext.JSON.decode(response.responseText);
				if (respObj.success == true) {
					Ext.MessageBox.alert('提示', respObj.message);
				} else {
					Ext.MessageBox.alert('提示', respObj.message);
				}
			},
			failure: function (response, opts) {
				Ext.MessageBox.alert('提示', 'Http请求失败, 请联系管理员查找问题');
			}
		});
	},
	/**
	 * 弹窗显示卖出建议的列表
	 */
	popupSuggests: function () {
		var myview = this.getView();
		var selRec = this._getSingleSelRec(myview.getSelectionModel().getSelection());
		if (!selRec) {
			return;
		}
		var slimsymbol = selRec.get('slimsymbol');
		var popWin = Ext.widget("window", {
			title: '卖出建议列表',
			layout: 'fit',
			width: 1450,
			height: 750,
			minWidth: 600,
			minHeight: 500,
			border: false,
			plain: true,
			modal: true,
			resizable: true,
			items: [{ xtype: "stockor.exec.form.ZenSelloutSuggestionGird" }]
		});
		var popWinPanel = popWin.getComponent(0); //获取form view
		var popWinViewModel = popWinPanel.getViewModel(); //获取view的viewmodel
		popWinViewModel.set('execHold.id', selRec.get('id'));
		popWinViewModel.set('execHold.slimsymbol', slimsymbol);
		popWinViewModel.set('execHold.stkname', selRec.get('name'));

		this.getView().add(popWin);
		popWin.show();

		//设置加载窗口的数据源
		popWinViewModel.getStore('zenSelloutSuggestionStore').load({
			params: { 'slimsymbol': slimsymbol }
		});
		var winheight = popWin.getHeight(); //获取初始化后窗口的宽度
		var winwidth = popWin.getWidth(); //获取初始化后窗口的高度
		if (winheight - 10 > screenY) { //判断窗口高度是否小于浏览器的窗口高度(留有10px的余量)
			popWin.setHeight(screenY - 30); //设置高度适应浏览器高度(底部留有30px余量，顶部还有10px)
			popWin.setWidth(winwidth + 30); //因为出现了滚动条，增加显示滚动条的宽度
		}
	},
	/**
	 * 判断选择记录条数, 只允许一条, 返回选择记录的id
	 */
	_getSingleSelRec: function (selRecords) {
		var selIds = null;
		if (selRecords.length == 0) {
			Ext.MessageBox.alert('信息提示', '请选择需要操作数据!');
			return null;
		}
		if (selRecords.length > 1) {
			Ext.MessageBox.alert('信息提示', '只能选择一条数据操作! 选择数:' + selRecords.length);
			return null;
		}
		return selRecords[0];
	},
	/**
	 * 合计选中行的利润额
	 */
	selectionChange: function (the, selected, eOpts) {
		//console.debug('selectionChange', selected);
		var myview = this.getView();
		var selRecords = myview.getSelectionModel().getSelection();

		var total = 0;
		for (i = 0; i < selRecords.length; i++) {
			selRec = selRecords[i];

			var unitCost = selRec.get('unitCost');
			var current = selRec.get('current');
			var holdVolume = selRec.get('holdVolume');
			if (current && holdVolume != 0) {
				total = total + (current - unitCost) * holdVolume;
			}
		}
		var myviewmodel = myview.getViewModel();
		myviewmodel.set('totalProfitSum', total);
		//console.debug('total', total);
	}
});